<?php
include_once 'ctype/base/baseField.php';

class Categories extends BaseField{
	var $template = "ctype/views/fields/categories.php";
	
	var $properties = array( //categoria padre
		"title"			=> "Categorias",
		"description" 	=> "Descripción del campo texto",
		"multiple"		=> FALSE
	);
	
	function Categories(){
		parent::BaseField();
		
		$this->ci->load->model( "Category_Model", "Categories");
		$this->ci->load->model( "Node_Model", "Nodes");
	}
	
	//@TODO funcion que obtendra los valores de las categorias a las que pertenece
	function view($node = NULL, $data = NULL){
		$value = $data;
		$name = $this->formName;
		$properties = $this->properties;
		$required = $this->required;
		
		$categoryParentId = -1;
		if(isset($properties['category']) && $properties['category'] != NULL){
			//@TODO
			$tmpCategory = $this->ci->Categories->get(array("url_name" => $properties['category'], "status" => "all"));
			if($tmpCategory !== FALSE && $tmpCategory != NULL){
				$categoryParentId = $tmpCategory->id;
			}
		}
		
		$categories = array();
		if($categoryParentId != -1){	
			$categories = $this->ci->Categories->get(array("parent" => $categoryParentId, "status" => "all"));
		}
		
		if($node != NULL){
			$selected_categories = $this->ci->Nodes->getCategories($node->id);
		}
		
		ob_start();
		eval('?>'.preg_replace("/;*\s*\?>/", "; ?>", str_replace('<?=', '<?php echo ', file_get_contents($this->template, TRUE))));
		$view = ob_get_contents();
		@ob_end_clean();
		
		return $view;
	}
	
	function save($node = NULL, $data = NULL){
		//Eliminamos las categorias anteriormente seleccionadas
		if($data != NULL && $node != NULL){
			if(is_array($data)){
				foreach($data as $category){
					//Eliminar la $category del nodo
					$this->ci->Nodes->deleteCategory($node->id, $category);
				}
			} else{
				//Eliminar la $category del nodo
				$this->ci->Nodes->deleteCategory($node->id, $data);
			}
		}
		
		//Obtenemos las categorias seleccionadas
		$categorias = $this->ci->input->post($this->formName);
		
		if($node != NULL){
			$this->ci->Nodes->addCategories($node->id, $categorias);
		}
		
		return $categorias;
	}
	
	function delete($node = NULL, $data = NULL){
		if($node != NULL && $data != NULL){
			if(is_array($data)){
				foreach($data as $category){
					//Eliminar la $category del nodo
					$this->ci->Nodes->deleteCategory($node->id, $category);
				}
			} else{
				//Eliminar la $category del nodo
				$this->ci->Nodes->deleteCategory($node->id, $data);
			}
		}
		
		return TRUE;
	}
}
?>
